<template>
  <div class="play-container">

    <div style="display: flex; margin-bottom: 20px;">
      <audio :src="nowVoice"></audio>

      <div class="question-container">
        <p style="margin-bottom: 7px;margin-top: 7px; text-align:left"  >根据您听完语音后的感觉，请您对该段音频中医生的各类语气（包括：{{tableData.map(e => e.label).join('、')}}）进行打分，分值越大表示对应的某种语气程度越深（即分值越大该类语气越明显）。语气含义如下：</p>

        <li class="def_note" v-for="(item, index) in tableData" :key="item.name">{{item.label}}：{{item.desc}}{{index == tableData.length - 1 ? '。' : '；'}}</li>
        
        <p style="margin-bottom:7px;margin-top: 7px;text-align:left; font-size: 18px" > 分值含义：“1”表示“没有”、“2”表示“很少有”、“3”表示“有点”、“4”表示“一般”、“5”表示“比较”、“6”表示“较多”、“7”表示“非常”。</p>

        <div >
          <div style="width: 60%; display: inline-block">
            <div :style="isPlaying ? 'cursor: not-allowed;' : 'cursor: pointer;'" @click="playVoice">
              <img :src="require('../assets/speakers.png')" style="margin-top: 0px; display: inline-block"/>
              <div style="color: dodgerblue; display: inline-block">{{isPlaying ? ('剩余播放次数：' + (replayCount - values.playCount + 1)) : '点击播放'}}</div>
            </div>
            <!--<div>00:{{timer >= 10 ? timer : ('0' + timer)}}</div>-->
          </div >
          <div class="h3-class" >共 {{totalCount}} 条，<br>第 {{values.currentMarkIndex}} 条。</div>


        </div>

        <el-table :data="tableData"
          v-loading="isFirst"
          :element-loading-text="timer==waitTime ? '请先点击上侧喇叭播放音频，听完音频后再作答' : timer + '秒后开始作答...'"
          element-loading-spinner='el-icon-timer'
          element-loading-background="rgba(255, 255, 255, 0.5)"
          >
          <el-table-column align="center" prop="label"  >
            <template slot="header" slot-scope="scope">
              <br><span class="score">分值</span>
            </template>
          </el-table-column>
          
          <el-table-column align="center"  >
            <template slot="header" slot-scope="scope"  style="margin-left:-20px">
              没有<br><span class="score"  >1</span>
            </template>
            <template slot-scope="scope" >
              <el-radio v-model="values[scope.row.name]" :label="1"  >&nbsp;</el-radio>
            </template>
          </el-table-column>
          
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              很少有<br><span class="score">2</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="2" >&nbsp;</el-radio>
            </template>
          </el-table-column>
    
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              有点<br><span class="score">3</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="3" >&nbsp;</el-radio>
            </template>
          </el-table-column>
          
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              一般<br><span class="score">4</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="4" >&nbsp;</el-radio>
            </template>
          </el-table-column>
          
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              比较<br><span class="score">5</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="5" >&nbsp;</el-radio>
            </template>
          </el-table-column>
          
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              较多<br><span class="score">6</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="6" >&nbsp;</el-radio>
            </template>
          </el-table-column>
          
          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              非常<br><span class="score">7</span>
            </template>
            <template slot-scope="scope">
              <el-radio v-model="values[scope.row.name]" :label="7" >&nbsp;</el-radio>
            </template>
          </el-table-column>


        </el-table>

      </div>
    </div>
    <div>
      <br>
    </div>

    <el-button
      v-if="totalCount > 1"
      :type="values.currentMarkIndex < totalCount ? 'primary': 'info'"
      :disabled="isFirst || values.currentMarkIndex >= totalCount"
      @click="nextVoice">
      下一条
    </el-button>
    <el-button
      :type="values.currentMarkIndex >= totalCount ? 'primary': 'info'"
      :disabled="isFirst || values.currentMarkIndex < totalCount"
      @click="finish">
      完成
    </el-button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        stopAfterPlaySecond:0,
        currentVoiceName:'',
        replayCount: 0,
        validVoiceName: '',
        validVoiceOrder: 0,
        source: null,
        timer: 10,
        waitTime: 10,
        isPlaying: false,
        totalCount: 13,
        nowVoice: "",
        voiceList: [],
        startTimeNum: 0,
        values: {
          peopleId: 0,
          wavId: '',
          startTime: '',
          endTime: '',
          durationTime: '',
          currentMarkIndex: 0,
          playCount: 0,
          wz: 0,
          jd: 0,
          zx: 0,
          rh: 0,
          qxh: 0,
          zz: 0,
          kx:0,
          zp:0,
          yl:0,
          gz:0,
          fn:0,
          xfd:0
        },
        tableData:[{
          label: '坚定',
          name: 'jd',
          desc: '说话人听起来是坚定、坚持和肯定的'
        },{
          label: '稳重',
          name: 'wz',
          desc: '说话者听起来是谨慎、深思熟虑和自我控制的'
        },{
          label: '支配',
          name: 'zp',
          desc: '说话者听起来是主导谈话、控制和支配听众的'
        },{
          label: '压力',
          name: 'yl',
          desc: '话者听起来是焦虑、紧张、苦恼的'
        },{
          label: '关注',
          name: 'gz',
          desc: '话者听起来是体谅人的、传递关心的和同情人的'
        },{
          label: '愤怒',
          name: 'fn',
          desc: '说话者听起来是生气的、气愤的、恼怒的或狂暴的'
        },{
          label: '兴奋度',
          name: 'xfd',
          desc: '表示说话者的声音有多积极或消极'
        }],
        intervalTimer: null,
        timeoutTimer: null,
        isFirst: true,
      };
    },
    mounted() {
      //进入页面时触发一次窗口resize事件，自动调整窗口大小
      setTimeout(() =>{
        window.dispatchEvent(new Event( 'resize'));
      },0);
      // 没有登录直接进入该页面
      if (!this.$store.state.peopleId) {
        this.$router.push('/login');
        
        return;
      }
      
      // this.init();
      this.getConfig();
    },
    methods: {
      getConfig() {
        var that = this;
        // that.$api.config.get()
        //   .then(function(response) {
        //      that.totalCount = response.data.peopleVoiceCount;
        //   });
        that.$api.config.get().then(function(response) {
          that.totalCount = response.data.peopleVoiceCount;
          that.validVoiceName = response.data.validVoiceName;
          that.validVoiceOrder = response.data.validVoiceOrder;

          if (response.data.markToneList) {
            let markToneList = response.data.markToneList.split(/\s*,\s*/);
            that.tableData = that.tableData.filter(function(e) {
              return markToneList.indexOf(e.name) >= 0
            });
          }

          if (response.data.stopAfterPlaySecond) {
            that.stopAfterPlaySecond = response.data.stopAfterPlaySecond;
          }

          that.replayCount = response.data.replayCount || 0;
          
          that.waitTime = response.data.answerAfterPlaySecond || 10;
          that.timer = that.waitTime;

          that.getOneVoiceName();
        });
      },
      playVoice() {
        var self = this;
        // if (self.isPlaying ) {
        if (self.isPlaying || !self.source) {
          return;
        }

        self.values.playCount++;
        self.isPlaying = true;
        if (self.values.playCount == 1) {
          self.values.startTime = self.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
          self.startTimeNum = new Date().getTime();
          // 倒计时
          self.intervalTimer = setInterval(function() {
            if (self.timer <= 0) {
              clearInterval(self.intervalTimer);
              self.isFirst = false;
              return;
            }
            self.timer--;
          }, 1000);
        }

        self.source.start(0);
        if (self.stopAfterPlaySecond && self.validVoiceName != self.currentVoiceName) {
          self.timeoutTimer = setTimeout(function() {
            self.isPlaying && self.source.stop();
          }, 1000 * self.stopAfterPlaySecond);
        }
      },
      getOneVoiceName() {
        var self = this;
        var nextPlay = '';
        if (self.validVoiceName && self.validVoiceOrder == self.values.currentMarkIndex + 1) {
          nextPlay = self.validVoiceName;
        }

        self.$api.playvoice.getOneVoiceName(self.$store.state.peopleId, nextPlay).then(function(res) {
          self.source = null;
          self.currentVoiceName = res.data.name;
          self.values.wavId = res.data.id;
          self.values.currentMarkIndex++;
          // 清空上次的标记数据
          self.tableData.forEach(function(e) {
            self.values[e.name] = 0;
          });
          self.timer = self.waitTime;
          self.values.playCount = 0;
          
          self.intervalTimer && clearInterval(self.intervalTimer);
          self.loadVoice(res.data.name);
        })
      },
      nextVoice() {
        var self = this;

        for (let i = 0; i < self.tableData.length; i++) {
          let name = self.tableData[i].name;
          if (!self.values[name]) {
            self.$confirm('所有内容都完成才能进行下一步操作', '提示', {
              showCancelButton: false,
              confirmButtonText: '确定',
              type: 'warning',
            });
            return;
          }
        }

        if (self.isPlaying) {
          self.timeoutTimer && clearTimeout(self.timeoutTimer);
          self.isPlaying = false;
          self.source.stop();
        }

        this.save(function(self) {
          // 加载下一条音频
          self.getOneVoiceName();
          self.isFirst = true;
        });
      },
      loadVoice(fileName) {
        var self = this;
        var myAudioContext = new (window.AudioContext || window.webkitAudioContext)();
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/voice-recognition/voice/getVoice?name=' + fileName, true);
        xhr.responseType = 'arraybuffer';
        xhr.addEventListener('load', function(event) {
          var request = event.target;
          self.source = myAudioContext.createBufferSource();
          myAudioContext.decodeAudioData(request.response, function(buffer) {
            self.source.buffer = buffer;
            self.source.connect(myAudioContext.destination);

            // 播放完成后的事件回调
            self.source.onended = () => {
              myAudioContext.close();
              self.intervalTimer && clearInterval(self.intervalTimer);
              self.isFirst = false;
              if (self.values.playCount <= self.replayCount) {
                self.isPlaying && self.loadVoice(self.currentVoiceName);
                //self.isPlaying = false;
                self.timer = self.waitTime;
              }
            }
          });
        }, false);

        xhr.addEventListener('loadend', function() {
            // 音频加载完成后才认为上一次播放已结束
            self.isPlaying = false;
        });

        xhr.send();
      },

      save(callback){
        var self = this;
        
        // 保存该条音频的标记数据
        self.values.peopleId = self.$store.state.peopleId;
        self.values.endTime = self.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        self.values.durationTime = Math.ceil((new Date().getTime() - self.startTimeNum) / 1000);
        
        self.$api.mark.save(self.values).then(function(res) {
          self.isPlaying && self.source.stop();
          callback(self);
        });
      },
      finish() {
        let self = this;
        for (let i = 0; i < self.tableData.length; i++) {
          let name = self.tableData[i].name;
          if (!self.values[name]) {
            self.$confirm('所有内容都完成才能进行下一步操作', '提示', {
              showCancelButton: false,
              confirmButtonText: '确定',
              type: 'warning',
            });
            return;
          }
        }
        
        self.save(function() {
          self.$router.push("/userdetail");
        });
      },

      getTbName(){
        let self = this;
        var b = [];
        for (var i=0;i<self.tableData.length;i++)
        {
          b.push(self.tableData[i]['label']);
        }
        var str1=b.join("、");
        // document.write(str1);
        return str1
      },

      judge(str) {
        //判断Hello是否与World相等，如果相等，返回true，如果不相等，返回false。
        return str == 'World' ? true : false;
      }

    },
  };
</script>

<style >

  .h3-class{
    width: 30%;
    display: inline-block;
    margin-bottom: 17px;
    font-size: 17px;
    border-left:1px solid dodgerblue;

  }
  .play-container {
    vertical-align: middle;
    border: 10px solid #DCDFE6;
    border-bottom: 10px;
    width: 600px;
    height: auto;
    margin:  auto;
    margin-bottom: 100px;
    margin-top: 40px;
    padding: 20px 10px 100px 10px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }
  .score{
    color: orange;
  }
  .question-container {
    width: 600px;
    font-size: 20px;
    margin-right:30px;
    margin-left: 30px;
    text-align: center;
  }
  i.el-icon-timer {
    font-size: 25px;
  }
  .notice-item{
    color: dodgerblue;
  }
  .ratio-size{
    font-size: 25px;
  }
  .el-radio__inner {
    border: 2px solid #DCDFE6;
    border-radius: 100%;
    width: 30px;
    height: 30px;
    background-color: #FFF;
    cursor: pointer;
    box-sizing: border-box;
  }
  .el-table .cell, .el-table th div {
    padding-right: 0px;
    /*padding: 0px;*/
  }
  .el-table .cell, .el-table th div, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
    padding-left: 0px;
    padding-right: 0px;
    /*padding: 0px;*/
  }
  /*.el-radio__label {*/
  /*  !*font-size: 0px;*!*/
  /*  padding-left: 0px;*/
  /*}*/

  /*element.style {*/
  /*  width: 100%;*/
  /*}*/
  .el-table td, .el-table th {
    /*padding-bottom: 4px ;*/
    padding-bottom: 10px ;
    /*padding-top: 4px ;*/
    padding-top: 10px ;
    min-width: 0;
  }
  .el-loading-spinner .el-loading-text {
    font-size: 20px;
  }
  .el-table {
    font-size: 20px;
    font-weight: bolder;
  }
  .el-table .cell {
    line-height: 25px;
  }

  .el-radio__label {
    font-size: 20px;
    padding-left: 3px;
  }
  .el-button {
    font-size: 20px;
    /*border-radius: 25px;*/
  }
  .def_note {
    color: dodgerblue;
    font-weight: bolder;
    text-align: left;
  }
  .el-message-box__content {
    font-size: 20px;
  }
</style>
